package com.cyh.structurealgorithm;

import java.util.ArrayList;

public class BinarySearch {
    public static void test() {
        int arr[] = {-8, -2, -2, -1, 3, 3, 5, 9, 10, 10, 11};
        int resIndex = binarySearch(arr, 0, arr.length - 1, 9);
        int resIndex2 = binarySearch(arr, 0, arr.length - 1, 100);
        System.out.println("查找的下标：resIndex = " + resIndex + " resIndex2 = " + resIndex2);

    }

    public static int binarySearch(int[] arr, int left, int right, int findVal) {
        if(left > right) {
            return -1;
        }
        int mid = (left + right) / 2;
        int midVal = arr[mid];
        if(findVal > midVal) {
            return binarySearch(arr, mid + 1, right, findVal);
        } else if(findVal < midVal) {
            return binarySearch(arr, left, mid -1, findVal);
        } else {
            return mid;
        }
    }

    //找到所有符合条件的下标
    public static ArrayList<Integer> binarySearch2(int[] arr, int left, int right, int findVal) {
        if(left > right) {
            return new ArrayList<>();
        }
        int mid = (left + right) / 2;
        int midVal = arr[mid];
        if(findVal > midVal) {
            return binarySearch2(arr, mid + 1, right, findVal);
        } else if(findVal < midVal) {
            return binarySearch2(arr, left, mid -1, findVal);
        } else {
            ArrayList<Integer> resIndexList = new ArrayList<>();
            int temp = mid - 1;
            while(true) {
                if(temp < 0 || arr[temp] != findVal) {
                    break;
                }
                resIndexList.add(temp);
                temp -= 1;
            }

            resIndexList.add(mid);

            temp = mid + 1;
            while(true) {
                if(temp > arr.length - 1 || arr[temp] != findVal) {
                    break;
                }
                resIndexList.add(temp);
                temp += 1;
            }

            return resIndexList;
        }
    }
}
